<template>
  <div class="uploadBox">
    <div class="uploadImg" v-if="curImg==null" @click="uploadImg1()">
      <!-- <van-icon name="plus" /><br> -->
      <!-- <span>请上传图片</span> -->
    </div>
    <img class="img" v-else :src="imgSrc" alt="" @click="preView">
    <!-- <input style="display: none;" type="file" accept="image/*" ref="realUpload"  @change="uploadImg($event)"/> -->
    <input style="display: none;"  ref="realUpload"  @change="uploadImg1()"/>
  </div>
</template>

<script>
import { ImagePreview } from 'vant';
import { UploadPictures,urlFun } from "@/api/index";
import {clickSureImg,getUnixTime,getNoce,getUpLoadSKey} from '@/utils/util';
import EXIF from 'exif-js'
  export default{
    name: 'UploadImg',
    props:['imgSrc'],
    data(){
      return {
        curImg: null,
      }
    },
    mounted() {
      if(this.imgSrc){
        // this.curImg = {};
        // this.$set(this.curImg,'FileUrl',this.imgSrc);
        this.$nextTick(()=>{
          this.curImg = this.imgSrc
        })
      }
    },
    methods:{
      upload(){
        this.$refs.realUpload.click()
      },
      preView(){
        // ImagePreview([
        //   this.curImg.FileUrl
        // ]);
        ImagePreview({
        images: [
          this.curImg
        ],
        closeable: true,
      });
      },
      uploadImg1(){
         let self = this;
       //走 app
          window.uploadImageFuc = this.uploadImageFuc = function (res) { // 回调方法
            if(res.ret == 1){
              res.image.forEach((c) => {
                console.log('c',c)
                // self.option.img = c.absolutePath;
                // self.option.autoCrop = true;
                // self.file_name = c.name;
                // let messageTxt = ''
                // if(self.curImg !== null){
                //   messageTxt='重新上传成功'
                // }else{
                //    messageTxt='图片上传成功'
                // }
                self.curImg = c;
                self.$emit('upload', self.curImg)
                // self.$Tips({
                //   content:messageTxt,

                //   icon:'correct'
                // })
              })
            }else{
                // self.$Tips({
                //   content:'上传失败',
                //   icon:'correct'
                // })
            }
          }
          selectImage({imageCount:1,uploadImageFuc: 'uploadImageFuc',returnType:1})
      },
      uploadImg(e){
        var that = this;
        let file = this.$refs['realUpload'].files[0];

        let formData = new FormData();
        var Orientation = 1;
        EXIF.getData(file, function() {
          var ver = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
          console.log(ver);
          if(ver&&ver[1]>=13||(ver[1]==13&&ver[2]>=4)){//ios13.4上传的图片是正常的显示格式，即不需要做旋转九十度处理
            Orientation = 1;
          } else {
            Orientation = EXIF.getTag(this, "Orientation");
          }
        });
        // let reader = new FileReader();
        // reader.readAsDataURL(file);
        if(file.size>10000000){//10M
          this.$Tips('图片不能大于10M');
          return
        }
        if(file.size>1000000){//1M 压缩
          // 创建一个reader
          let reader = new FileReader();
          // 将图片2将转成 base64 格式
          reader.readAsDataURL(file);
          var img = new Image;
          // 读取成功后的回调
          reader.onloadend = function (e) {
            var canvas = document.createElement("canvas"),
                drawer = canvas.getContext("2d");
            img.src = this.result;
            // console.log(img)
       
            img.onload = function () {
                canvas.width = 1080;
                canvas.height =canvas.width * (this.height/this.width);
                switch(Orientation){
                  case 6:     // 旋转90度
                    // canvas.width = imgHeight;
                    // canvas.height = imgWidth;
                    drawer.rotate(Math.PI / 2);
                    // drawer.fillRect(0, 0, canvas.width, canvas.height);
                    drawer.drawImage(this,  0, -canvas.height, canvas.width, canvas.height);
                    //alert('进入6了')

                    break;
                  case 3:     // 旋转180度
                    drawer.rotate(Math.PI);
                    drawer.drawImage(this, -canvas.width, -canvas.height,canvas.width,canvas.height);
                    break;
                  case 8:     // 旋转-90度
                    // canvas.width = imgHeight;
                    // canvas.height = imgWidth;
                    drawer.rotate(3 * Math.PI / 2);
                    drawer.drawImage(this, -canvas.width, 0,canvas.width,canvas.height);
                    break;
                  default:
                    drawer.drawImage(this,  0, 0, canvas.width, canvas.height);
                    break;
                }
                // console.log(drawer,89)
                canvas.toBlob(function(blob) {
                  formData.append("file", blob, file.name);//+file.type.split('/')[1]
                  let skey = getUpLoadSKey("web1",new Date().getTime() + Math.ceil(Math.random()*1000),getNoce(),'v1.0',getUnixTime());
                 UploadPictures(formData,skey).then(res=>{
                    // console.log(res.Value,this.curImg,89)
                    if(res.ResultCode==1){
                      let messageTxt = ''
                      if(that.curImg !== null){
                        messageTxt='重新上传成功'
                      }else{
                        messageTxt='图片上传成功'
                      }
                      that.curImg = res.Value;
                      that.$emit('upload', res.Value.FileUrl)
                      that.$Tips({
                          content:messageTxt,
                          icon:'correct'
                        })
                    } else {
                      that.$Tips(res.ResultMessage);
                    }
                  }).catch(err => {
                    console.log(err)
                    that.$Tips('图片上传失败，请重试')
                    // this.$dialog.alert({
                    //   message: err.toString()
                    // });
                  })
                }, file.type || 'image/png');
            }

          }
        } else {
            formData.append("file", file,file.name);
            let skey = getUpLoadSKey("web1",new Date().getTime() + Math.ceil(Math.random()*1000),getNoce(),'v1.0',getUnixTime());
            UploadPictures(formData,skey).then(res=>{
              console.log(res,108)
              if(res.ResultCode==1){
                let messageTxt = ''
                if(this.curImg !== null){
                  messageTxt='重新上传成功'
                }else{
                   messageTxt='图片上传成功'
                }
                this.curImg = res.Value;
                this.$emit('upload', res.Value.FileUrl)
                this.$Tips({
                  content:messageTxt,
                  icon:'correct'
                })
              } else {
                this.$Tips(res.ResultMessage);
              }
            }).catch(err => {
              console.log(err)
              this.$Tips('图片上传失败，请重试')
            })
          }
      },

    },
    watch:{
      imgSrc(val){
        if(!this.curImg){
          console.log('----------')
          // this.curImg = {};
          this.curImg = val
          // this.$set(this.curImg,'FileUrl',val);
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .uploadBox{
    height: 100%;
    width: 100%;
    position: relative;
    /* opacity: 0; */
  }
  .uploadImg{
        width: 3.2rem;
        height: 3.2rem;
        border-radius: .4rem;
        background: url('~@/assets/img/dot-upload.png') #EFF1F3 no-repeat center 1.1rem;
        background-size: 20% auto;
        position: relative;
        &::after{
            content: '请上传图片,不超过10M';
            position: absolute;
            bottom: .7rem;
            width: 100%;
            text-align: center;
            font-size: .24rem;
            color: #999;
        }
    }
  .uploadBox .img{
    width: 3.2rem;
    height: 3.2rem;
    border-radius: .4rem;
    position: absolute;
    left: 0;
    top: 0;
  }
  .uploadBox .pluginBG{
      width: 100%;
      height: 100%;
  }
  .uploadBox .pluginBG i{
    font-size: .6rem;
  }
  .uploadBox .pluginBG span{
    font-size:0.24rem;
    font-weight:400;
    margin-top: .32rem;
    display: inline-block;
  }
</style>
